package com.lottery.im.module.chat.ui;

import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.lottery.im.MyApplication;
import com.lottery.im.R;
import com.lottery.im.api.result.entity.SectionProfile;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.module.chat.adapter.SelectSearchProfileAdapter;
import com.lottery.im.module.setting.ui.ProfileFragment;
import com.lottery.im.module.tim.model.FriendProfile;
import com.lottery.im.module.tim.model.FriendshipInfo;
import com.lottery.im.module.tim.model.GroupInfo;
import com.lottery.im.module.tim.model.GroupProfile;
import com.lottery.im.module.tim.model.ProfileSummary;
import com.lottery.im.util.StatusBarHelper;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.TIMValueCallBack;
import com.tencent.imsdk.ext.group.TIMGroupDetailInfo;
import com.tencent.imsdk.ext.group.TIMGroupManagerExt;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 搜索用户、群
 */
public class SearchUserGroupFragment extends BaseSwipeFragment implements View.OnKeyListener {

  private final static String CONTENT_KEY = "CONTENT_KEY";

  public static SearchUserGroupFragment create(String content) {
    SearchUserGroupFragment fragment = new SearchUserGroupFragment();
    Bundle b = new Bundle();
    b.putString(CONTENT_KEY, content);
    fragment.setArguments(b);
    return fragment;
  }

  @BindView(R.id.et_search) EditText mEtSearch;
  @BindView(R.id.list) RecyclerView mList;
  @BindView(R.id.tv_empty_tip) TextView mTvEmptyTip;
  @BindView(R.id.iv_clear) ImageView mIvClear;

  private List<SectionProfile> mProfiles;
  private SelectSearchProfileAdapter mAdapter;

  @Override protected int getLayoutResId() {
    return R.layout.fragment_search_usergroup;
  }

  @Override protected void initPresenter() {
    initView();
  }

  private void initView() {
    mEtSearch.setOnKeyListener(this);

    mProfiles = new ArrayList<>();
    mList.setLayoutManager(new LinearLayoutManager(mActivity));
    RecyclerViewDivider.with(mActivity)
        .color(ContextCompat.getColor(mActivity, R.color.windowBackground))
        .size((int) mActivity.getResources().getDimension(R.dimen.line_size))
        .hideLastDivider()
        .build()
        .addTo(mList);
    mAdapter = new SelectSearchProfileAdapter(mProfiles);
    mAdapter.setOnItemClickListener((adapter, view, position) -> {
      if (mProfiles.get(position).isHeader) return;

      ProfileSummary profile = mProfiles.get(position).t;

      if (profile instanceof GroupProfile) {
        startFragment(SearchGroupProfileFragment.create((GroupProfile) profile));
      } else if (profile instanceof FriendProfile) {
        if (profile.getIdentify().equals(MyApplication.getInstance().getThirdAccId())) {
          // 用户自己
          startFragment(new ProfileFragment());
        } else {
          startFragment(UserProfileFragment.create(profile.getIdentify()));
        }
      }
    });
    mList.setAdapter(mAdapter);

    String content = getArguments().getString(CONTENT_KEY);
    if (!TextUtils.isEmpty(content)) {
      mEtSearch.setText(content);
      search();
    }
  }

  @OnClick({ R.id.iv_back, R.id.iv_clear, R.id.tv_search }) public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.iv_back:
        popBackStack();
        break;
      case R.id.iv_clear:
        mEtSearch.setText("");
        break;
      case R.id.tv_search:
        search();
        break;
    }
  }

  @OnTextChanged(value = R.id.et_search, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
  void afterTextChanged(Editable content) {
    if (TextUtils.isEmpty(content.toString())) {
      mIvClear.setVisibility(View.GONE);
    } else {
      mIvClear.setVisibility(View.VISIBLE);
    }
  }

  @Override public boolean onKey(View v, int keyCode, KeyEvent event) {
    if (event.getAction() != KeyEvent.ACTION_UP) {   // 忽略其它事件
      return false;
    }

    switch (keyCode) {
      case KeyEvent.KEYCODE_ENTER:
        search();
        return true;
      default:
        return false;
    }
  }

  private void search() {
    String content = mEtSearch.getText().toString();
    if (TextUtils.isEmpty(content)) {
      showToast("请输入搜索内容");
      return;
    }
    hideKeyBoard();
    mProfiles.clear();

    if (FriendshipInfo.getInstance().isFriend(content)) {
      // 是好友，就无需继续搜索
      mProfiles.add(new SectionProfile(true, "找人"));
      FriendProfile profile = FriendshipInfo.getInstance().getProfile(content);
      mProfiles.add(new SectionProfile(profile));
      mAdapter.notifyDataSetChanged();
      mList.setVisibility(View.VISIBLE);
      mTvEmptyTip.setVisibility(View.GONE);
      return;
    }
    if (GroupInfo.getInstance().isInGroup(content)) {
      GroupProfile groupProfile =
          GroupInfo.getInstance().getGroupProfile(GroupInfo.publicGroup, content);
      // 是自己加入过的群组，就无需继续搜索
      mProfiles.add(new SectionProfile(true, "找群"));
      mProfiles.add(new SectionProfile(groupProfile));
      mAdapter.notifyDataSetChanged();
      mList.setVisibility(View.VISIBLE);
      mTvEmptyTip.setVisibility(View.GONE);
      return;
    }
    showLoadingDialog();
    // 先搜人 再搜群
    toSearchFriend(content);
  }

  private void toSearchFriend(String content) {
    TIMFriendshipManager.getInstance().getUsersProfile(Collections.singletonList(content),
        new TIMValueCallBack<List<TIMUserProfile>>() {
          @Override public void onError(int i, String s) {
            toSearchGroup(content);
          }

          @Override public void onSuccess(List<TIMUserProfile> timUserProfiles) {
            if (null != timUserProfiles && timUserProfiles.size() > 0) {
              mProfiles.add(new SectionProfile(true, "找人"));
              for (TIMUserProfile profile : timUserProfiles) {
                mProfiles.add(new SectionProfile(new FriendProfile(profile)));
              }
            }
            toSearchGroup(content);
          }
        });
  }

  private void toSearchGroup(String content) {
    TIMGroupManagerExt.getInstance()
        .getGroupPublicInfo(Collections.singletonList(content),
            new TIMValueCallBack<List<TIMGroupDetailInfo>>() {
              @Override
              public void onError(int i, String s) {
                cancelLoadingDialog();
                refreshResult();
              }

              @Override
              public void onSuccess(List<TIMGroupDetailInfo> timGroupDetailInfos) {
                cancelLoadingDialog();
                if (null != timGroupDetailInfos || timGroupDetailInfos.size() > 0) {
                  mProfiles.add(new SectionProfile(true, "找群"));
                  for (TIMGroupDetailInfo profile : timGroupDetailInfos) {
                    mProfiles.add(new SectionProfile(new GroupProfile(profile)));
                  }
                  refreshResult();
                }
              }
            });
  }

  private void refreshResult() {
    if (mProfiles.size() == 0) {
      mList.setVisibility(View.GONE);
      mTvEmptyTip.setVisibility(View.VISIBLE);
    } else {
      mAdapter.notifyDataSetChanged();
      mList.setVisibility(View.VISIBLE);
      mTvEmptyTip.setVisibility(View.GONE);
    }
  }

  @Override public void onResume() {
    super.onResume();
    StatusBarHelper.setStatusBarDarkMode(getActivity());
  }
}
